﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using System.Text;
using System.IO;
using System.Drawing;

using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Reflection; 

namespace WebSite.admin.product
{
    public partial class goods_add04 : BaseAdmin
    {

        // Methods
        private void AddPicture(string imgpath, string imgnote, string albumid)
        {
            MarkWater(imgpath, "PicBase/warter.png");
            SQLAccess.DoSql("insert into DB_Shoppic(picurl,content,proid) values('" + imgpath + "','" + imgnote + "'," + albumid + ")");
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {

            if (base.Request.QueryString["gid"] != null)
            {
                HttpFileCollection files = HttpContext.Current.Request.Files;
                StringBuilder builder = new StringBuilder("");
                string[] strArray = base.Request.Form["text"].Split(new char[] { ',' });
                string albumid = base.Request.QueryString["gid"].ToString();
                for (int i = 0; i < files.Count; i++)
                {
                    if (files[i].FileName.Length > 0)
                    {
                        HttpPostedFile file = files[i];
                        if ((file.ContentLength / 1024) > 300)
                        {
                            builder.Append(Path.GetFileName(file.FileName) + "---不能大于300k<br>");
                            break;
                        }
                        string extension = Path.GetExtension(file.FileName);
                        if (((extension != ".jpg") && (extension != ".JPG")) && ((extension != ".gif") && (extension != ".GIF")))
                        {
                            builder.Append(Path.GetFileName(file.FileName) + "---图片格式不对，只能是jpg或gif<br>");
                            break;
                        }
                    }
                }
                if (builder.Length <= 0)
                {
                    string str3 = "pic001";
                    string path = base.Server.MapPath("../../uploadfile/PicBase") + @"\" + str3;
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    Random random = new Random();
                    int num2 = 1;
                    this.upcontent(albumid);
                    for (int j = 0; j < files.Count; j++)
                    {
                        HttpPostedFile file2 = files[j];
                        string fileName = "";
                        string str6 = "";
                        string imgpath = "";
                        fileName = Path.GetFileName(file2.FileName);
                        string str8 = random.Next(100, 0x5f5e100).ToString() + num2.ToString();
                        string str9 = DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + str8;
                        if (fileName.Length > 0)
                        {
                            str6 = Path.GetExtension(file2.FileName);
                            string filename = path + @"\" + str9 + str6;
                            file2.SaveAs(filename);
                            imgpath = @"PicBase\" + str3 + @"\" + str9 + str6;
                        }
                        if (str6.ToString() != "")
                        {
                            this.AddPicture(imgpath, strArray[j], albumid);
                        }
                        num2++;
                    }
                    ExtAspNet.Alert.Show("商品相册更新成功！", "", "window.location.href='goods_add04.aspx?gid=" + base.Request.QueryString["gid"] + "'");
                }
            }
            else
            {
                ExtAspNet.Alert.Show("请先添加商品基本信息！");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
     
         
            if (!base.IsPostBack && (base.Request.QueryString["gid"] != null))
            {
                this.upbind();
            }
        }

        private void upbind()
        {
            DataSet set = SQLAccess.GreatDs("select * from DB_Shoppic where proid=" + base.Request.QueryString["gid"] + " order by picid asc");
            this.DataList1.DataSource = set;
            this.DataList1.DataBind();
            if (((base.Request.QueryString["picid"] != null) && (base.Request.QueryString["action"] != null)) && (base.Request.QueryString["action"].ToString() == "del"))
            {
                SQLAccess.DoSql("delete from DB_Shoppic where picid=" + base.Request.QueryString["picid"].ToString() + "");
                ExtAspNet.Alert.Show("删除成功！", "", "window.location.href='goods_add04.aspx?gid=" + base.Request.QueryString["gid"] + "'");
            }
        }

        private void upcontent(string albumid)
        {
            string sql = "select * from DB_Shoppic where proid=" + albumid + " order by picid asc";
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            if (table.Rows.Count > 0)
            {
                foreach (DataRow row in table.Rows)
                {
                    SQLAccess.DoSql("update [DB_Shoppic] set [content]='" + base.Request.Form["content_" + row["picid"].ToString()] + "' where picid=" + row["picid"].ToString() + "");
                }
            }
        }

     

        /// <summary> 
        /// 给图片上水印 
        /// </summary> 
        /// <param name="filePath">原图片地址</param> 
        /// <param name="waterFile">水印图片地址</param> 
         void MarkWater(string filePath, string waterFile)
        {
            //GIF不水印 
            int i = filePath.LastIndexOf(".");
            string ex = filePath.Substring(i, filePath.Length - i);
            if (string.Compare(ex, ".gif", true) == 0)
            {
                return;
            }
            string BasePath = Server.MapPath("/uploadFile/");
            string ModifyImagePath = BasePath + filePath;//修改的图像路径 
            int lucencyPercent = 40;
            System.Drawing.Image modifyImage = null;
            System.Drawing.Image drawedImage = null;
            Graphics g = null;
            try
            {
                //建立图形对象 
                modifyImage = System.Drawing.Image.FromFile(ModifyImagePath, true);
                drawedImage = System.Drawing.Image.FromFile(BasePath + waterFile, true);
                g = Graphics.FromImage(modifyImage);
                //获取要绘制图形坐标 
                int x = (modifyImage.Width - drawedImage.Width) /2;
                int y = (modifyImage.Height - drawedImage.Height) /2;
                //设置颜色矩阵 
                float[][] matrixItems ={ 
            new float[] {1, 0, 0, 0, 0}, 
            new float[] {0, 1, 0, 0, 0}, 
            new float[] {0, 0, 1, 0, 0}, 
            new float[] {0, 0, 0, (float)lucencyPercent/100f, 0}, 
            new float[] {0, 0, 0, 0, 1}};

                ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
                ImageAttributes imgAttr = new ImageAttributes();
                imgAttr.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                //绘制阴影图像 
                g.DrawImage(drawedImage, new Rectangle(x, y, drawedImage.Width, drawedImage.Height), 0, 0, drawedImage.Width, drawedImage.Height, GraphicsUnit.Pixel, imgAttr);
                //保存文件 
                string[] allowImageType = { ".jpg", ".gif", ".png", ".bmp", ".tiff", ".wmf", ".ico" };
                FileInfo fi = new FileInfo(ModifyImagePath);
                ImageFormat imageType = ImageFormat.Gif;
                switch (fi.Extension.ToLower())
                {
                    case ".jpg": imageType = ImageFormat.Jpeg; break;
                    case ".gif": imageType = ImageFormat.Gif; break;
                    case ".png": imageType = ImageFormat.Png; break;
                    case ".bmp": imageType = ImageFormat.Bmp; break;
                    case ".tif": imageType = ImageFormat.Tiff; break;
                    case ".wmf": imageType = ImageFormat.Wmf; break;
                    case ".ico": imageType = ImageFormat.Icon; break;
                    default: break;
                }
                MemoryStream ms = new MemoryStream();
                modifyImage.Save(ms, imageType);
                byte[] imgData = ms.ToArray();
                modifyImage.Dispose();
                drawedImage.Dispose();
                g.Dispose();
                FileStream fs = null;
                File.Delete(ModifyImagePath);
                fs = new FileStream(ModifyImagePath, FileMode.Create, FileAccess.Write);
                if (fs != null)
                {
                    fs.Write(imgData, 0, imgData.Length);
                    fs.Close();
                }
            }
            finally
            {
                try
                {
                    drawedImage.Dispose();
                    modifyImage.Dispose();
                    g.Dispose();
                }
                catch
                {
                }
            }
        } 



    }
}